<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 示例接口
 */
class Wxapp extends Api
{
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * @return void
     * 获取电话
     */
    public function getmobile(){


        $code = $this->request->param('code');

        $appid='wx2b0b765c23fd0f3b';
        $key='821eb7b8b1b0f37ebe4018c21914fea0';


        $content = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $key);

        $content=json_decode($content,true);

        $access_token=$content['access_token'];



        $url='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;


        $data  = json_encode(['code'=>$code]);

        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        $ret= json_decode($output,true);



        if($ret['errcode']!=0){
            $this->error('获取手机号失败');
        }

        $mobile=$ret['phone_info']['phoneNumber'];

        $ret = $this->auth->loginformobile($mobile);

        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


}